package com.scs.application.modules.upms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.service.TreeServiceImpl;
import com.scs.application.modules.upms.consts.DictConsts;
import com.scs.application.modules.upms.entity.Menu;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.mapper.MenuMapper;
import com.scs.application.modules.upms.mapper.UserMapper;
import com.scs.application.modules.upms.request.MenuQueryRequest;
import com.scs.application.modules.upms.service.MenuService;
import com.scs.application.modules.upms.vo.MenuVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 */
@AllArgsConstructor
@Service
public class MenuServiceImpl extends TreeServiceImpl<MenuMapper, Menu> implements MenuService {

    private final UserMapper userMapper;

    @Override
    public List<Menu> list(MenuQueryRequest request) {
        List<Menu> list = this.list(Wrappers.<Menu>query()
                .eq(request.getParentId() != null, "parent_id" , request.getParentId())
                .orderByAsc("sort")
        );
        return list;
    }

    @Override
    public IPage<MenuVO> page(MenuQueryRequest request) {
        return this.baseMapper.page(request.getPage(), request);
    }

    @Override
    public List<Menu> getUserMenu(String userId, boolean excludeButton) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Collections.emptyList();
        }
        if (GlobalConsts.YES_STR.equalsIgnoreCase(user.getIsAdmin())) {
            return this.baseMapper.selectList(Wrappers.<Menu>query()
                    .ne(excludeButton, "type" , DictConsts.MENU_TYPE_BUTTON)
            );
        }
        return this.baseMapper.getUserMenu(userId, excludeButton);
    }


    @Override
    public List<Menu> getUserAppMenu(String userId, boolean excludeButton) {

        List<Menu> menus = getUserMenu(userId, excludeButton);

        return menus.stream().filter(o -> o.getFlagApp() && !o.getName().equalsIgnoreCase("app")).collect(Collectors.toList());
    }

    @Override
    public List<String> getPermissions(String userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Collections.emptyList();
        }
        if (GlobalConsts.YES_STR.equalsIgnoreCase(user.getIsAdmin())) {
            return this.baseMapper.selectObjs(Wrappers.<Menu>query().select("permissions").isNotNull("permissions").ne("permissions" , ""))
                    .stream().map(o -> o.toString()).collect(Collectors.toList());
        }
        return this.baseMapper.getUserPermissions(userId);
    }


}
